import json
import copy
from django.template import Library
from django.conf import settings
from django.urls import reverse
from django.utils.safestring import mark_safe
from urllib.parse import quote_plus

register = Library()


@register.simple_tag
def loop_counter(request, counter):
    page = request.GET.get('page', '1')
    if not page.isdecimal():
        page = '1'
    page = int(page)
    if page < 1:
        page = 1
    return (page - 1) * 20 + counter


@register.simple_tag
def url_plus(request, name, *args, **kwargs):
    prev = reverse(name, args=args, kwargs=kwargs)
    # print(request.path)
    # print(request.path_info)
    #
    # print(request.get_full_path())
    # print(request.get_full_path_info())
    current_url = request.get_full_path()
    param = quote_plus(current_url)
    return f"{prev}?redirect={param}"


@register.simple_tag
def getattr_plus(row, name):
    return getattr(row, name)


@register.simple_tag
def render_td(request, row, group):
    key, value = group
    if key == 'field':
        return getattr(row, value)
    else:
        return value(request, row)
